/*
 * @ProjectName: 编程学习
 * @Copyright:   2019 HangZhou Yi Dev, Ltd. All Right Reserved.
 * @address:     https://yiyuery.github.io/
 * @date:        2019/5/20 20:57
 * @email:       xiazhaoyang@live.com
 * @description: 本内容仅限于编程技术学习使用，转发请注明出处.
 */
package com.example.common.api.controlller;

import com.example.common.api.base.response.ResponseJson;
import com.example.common.api.exception.AbstractException;
import com.example.common.api.exception.code.ApiErrorCode;
import com.example.common.api.validation.ValidateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author Yi
 * @version v1.0.0
 * @date 2019-07-06 19:42
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2019-07-06
 * @modify reason: {方法名}:{原因}
 * ...
 */
@Slf4j
public abstract class BaseApiController {

    /**
     * 校验参数非空
     * @param obj
     */
    protected <T> void assertNotNull(T obj){
        ValidateUtil.requireNotSatisfyThrowException(Objects::nonNull,obj);
        if(obj instanceof Collection){
            ValidateUtil.requireNotSatisfyThrowException(CollectionUtils::isNotEmpty,(Collection<?>) obj);
        }
    }
    /**
     * 校验参数非空
     * @param obj
     */
    protected void assertNotNull(Object obj,String paramName){
        ValidateUtil.requireNotSatisfyThrowException(Objects::nonNull,obj,String.format("param `%s` can't be null!",paramName));
    }

    /**
     * 校验参数是否是合法范围
     * - depend on enum
     * @param type
     * @param optCodes
     * @param paramName
     * @param <T>
     */
    protected <T> void assertNotIllegalRange(T code, Collection<T> codes, String paramName){
        assertNotNull(codes);
        ValidateUtil.requireNotSatisfyThrowException(codes::contains,code,String.format("param `%s` not in legal range!",paramName));
    }

    /**
     * 系统异常处理
     * @param resp
     * @param e
     */
    protected void handleException(ResponseJson resp,Throwable e){
        resp.fail(ApiErrorCode.SYSTEM_ERROR.getCode(),"system error");
        log.error("request fail with errorCode:{},description:{}",ApiErrorCode.SYSTEM_ERROR.getErrorCode(),"system error");
    }

    /**
     * 业务异常处理
     * @param resp
     * @param e
     */
    protected void handleException(ResponseJson resp, AbstractException e){
        resp.fail(e.getErrorCode(),e.getErrorMessage());
        log.error("request fail with errorCode:{},description:{}",e.getErrorCode(),e.getErrorMessage());
    }
}
